#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/msg.h>

#define MSG_SIZE_MAX    512
#define MSG_TYPE_MAX    10

typedef struct msg {
    long int msgtype;
    char msg[MSG_SIZE_MAX];
} msg_t;

int main(int argc, char *argv[]) {
    msg_t msg;
    int msgkey = 0;
    int msgid = -1;
    char buf[BUFSIZ];

    if (argc != 3) {
        printf("error: invalid argument!\n");
        printf("usage: <app> <msgid> <msgtype>\n");
        exit(EXIT_FAILURE);
    }

    msgkey = atoi(argv[1]);
    msg.msgtype = (long int)atoi(argv[2]);
    msgid = msgget((key_t)msgkey, 0666 | IPC_CREAT);
    if (msgid == -1) {
        fprintf(stderr, "msgget failed with error: %s\n", strerror(errno));
        exit(EXIT_FAILURE);
    }

    while (1) {
        printf("Enter message: ");
        fgets(buf, BUFSIZ, stdin);
        strcpy(msg.msg, buf);
        if (msgsnd(msgid, (void *)&msg, MSG_SIZE_MAX, 0) == -1) {
            fprintf(stderr, "msgsnd failed with error: %s\n", strerror(errno));
            exit(EXIT_FAILURE);
        }

        if (!strncmp(buf, "end", 3)) {
            break;
        }
    }

    exit(EXIT_SUCCESS);
}
